<?php

namespace App\Admin\Controllers\Mp;

use App\Admin\Actions\Extensions\Mp\CustomMenuButton;
use App\Admin\Actions\Extensions\Mp\FreePublishFormButton;
use App\Admin\Actions\Extensions\Mp\FreePublishNoticeButton;
use App\Admin\Actions\Extensions\Mp\MpMaterialButton;
use App\Admin\Actions\Extensions\Mp\MpMessageButton;
use App\Admin\Actions\Extensions\Mp\MpMessageReplyButton;
use App\Admin\Actions\Grid\Mp\FreePublishMaterialAction;
use App\Admin\Actions\Grid\Mp\FreePublishSubmitAction;
use App\Admin\Repositories\Mp\WxMpFreePublish;
use App\Jobs\Mp\PublishGetStatusJob;
use App\Models\Mp\WxMpFreePublish as WxMpFreePublishModel;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Dcat\Admin\Layout\Content;

class WxMpFreePublishController extends AdminController
{

    public function index(Content $content)
    {
        return $content
            ->header('公众号推送')
            ->description('在你创建一个内容后，先手动同步一次（操作：新增草稿），之后不管你重新编辑，还是删除，都会与微信公众后台的草稿同步')
            ->body($this->grid());
    }

    public function free_publish_select(Request $request){
        $q = $request->get('q');
        return  WxMpFreePublishModel::where('parent_id', 0)->where(function ($query) use ($q) {
            if(is_numeric($q)){
                $query->orWhere('id', $q)
                    ->orWhere('title', 'like', '%' . $q . '%')
                    ->orWhere('author', 'like', '%' . $q . '%')
                    ->orWhere('media_id', 'like', '%' . $q . '%')
                    ->orWhere('article_id', 'like', '%' . $q . '%');
            }else{
                $query->orWhere('title', 'like', '%' . $q . '%')
                    ->orWhere('author', 'like', '%' . $q . '%')
                    ->orWhere('media_id', 'like', '%' . $q . '%')
                    ->orWhere('article_id', 'like', '%' . $q . '%');;
            }
        })->paginate(null, ['id', 'title as text']);
    }

    protected $publish_status = [
        0 => '成功',
        1 => '发布中',
        2 => '原创失败',
        3 => '常规失败',
        4 => '平台审核不通过',
        5 => '成功后用户删除所有文章',
        6 => '成功后系统封禁所有文章'
    ];

    protected $status_colors = [
        0 => 'green',       // 成功
        1 => 'blue',        // 发布中
        2 => 'red',         // 原创失败
        3 => 'orange',      // 常规失败
        4 => 'purple',      // 平台审核不通过
        5 => 'gray',        // 成功后用户删除所有文章
        6 => 'black'        // 成功后系统封禁所有文章
    ];
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WxMpFreePublish(), function (Grid $grid) {
            $grid->quickSearch(['id', 'title', 'media_id', 'article_id', 'content_source_url'])->placeholder('搜索ID，标题，草稿ID，文章ID...')->width(40);
            $grid->id('ID')->bold()->sortable();
            $grid->order->orderable();
            $grid->title->tree(true); // 开启树状表格功能
//            $grid->order->editable();
//            $grid->column('media_id');
//            $grid->column('article_id');
            $grid->column('author');
//            $grid->column('digest')->limit(20);
            $grid->column('thumb_url')->image();
            $grid->column('content_source_url')->display(function ($v){
                if($v){
                    return '<a href="'.$v.'" target="_blank">原文链接</a>';
                }
                return '';
            });
            $grid->column('need_open_comment')->switch();
            $grid->column('only_fans_can_comment')->switch();
            $grid->column('publish_status')->using($this->publish_status)->label($this->status_colors);
            $grid->column('article_url')->display(function ($v){
                if(!_empty_($this->publish_id) && _empty_($this->article_id)){
                    PublishGetStatusJob::dispatch($this->publish_id);
                }
                if($v){
                    return '<a href="'.$v.'" target="_blank">公众号链接</a>';
                }
                return '';
            });

            $grid->column('add_draft_time')->display(function ($v){
                if($v){
                    return format_datetime($v);
                }
                return '';
            });
            $grid->updated_at->display(function ($v){
                if($v){
                    return format_datetime($v);
                }
                return '';
            })->sortable();

            $grid->tools([
                new FreePublishFormButton(),
                new FreePublishNoticeButton(),
                new CustomMenuButton(),
                new MpMessageReplyButton(),
                new MpMessageButton(),
                new MpMaterialButton()
            ]);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append((new FreePublishMaterialAction())->setKey($this->id));
                $actions->append((new FreePublishSubmitAction())->setKey($this->id));
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('slug');
                $filter->like('name');
                $filter->like('http_path');
            });

        });

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxMpFreePublish(), function (Show $show) {
            $show->field('id');
            $show->field('parent_id');
            $show->field('order');
            $show->field('media_id');
            $show->field('title');
            $show->field('author');
            $show->field('digest');
            $show->field('content');
            $show->field('content_source_url');
            $show->field('thumb_url');
            $show->field('thumb_media_id');
            $show->field('need_open_comment');
            $show->field('only_fans_can_comment');
            $show->field('pic_crop_235_1');
            $show->field('pic_crop_1_1');
            $show->field('add_draft_time');
            $show->field('hope_publish_time');
            $show->field('publish_id');
            $show->field('publish_status');
            $show->field('article_id');
            $show->field('article_url');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxMpFreePublish(), function (Form $form) {
            $form->display('id');
            $form->text('order')->default(0)->display(false);
            $form->select('parent_id', '父级')->options(function ($id) {
                if($id){
                    $publish = \App\Models\Mp\WxMpFreePublish::find($id);
                    if ($publish) {
                        return [$publish->id => $publish->title];
                    }
                }
            })->ajax('mp/free_publish/select')->saving(function ($parent_id) {
                if(_empty_($parent_id)){
                    return 0;
                }
                return $parent_id;
            })->help('提示：这个针对的是多篇图文类型')->default(0);
            $form->text('title')->required();
            $form->text('author')->maxLength(8);
            $form->textarea('digest');
            $form->html(function () {
                return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">提示: 图片限制1m（微信官方限制），暂不支持上传视频，音频等</div>';
            }, '');
            if(__system_is_model_enable('laradocs', 'dcat-neditor')){
                $form->neditor('content');
            }else{
                $form->editor('content');
            }
            $form->text('content_source_url');
            $form->image('thumb_url')->url('files/uploads')->autoUpload()->required();
//            $form->text('thumb_media_id');
            $form->switch('need_open_comment')->default(1);
            $form->switch('only_fans_can_comment')->default(0);
//            $form->text('pic_crop_235_1')->required();
//            $form->text('pic_crop_1_1')->required();

            $form->display('created_at');
            $form->display('updated_at');

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    return $form->response()->error('权限不足，不可以删除其他分站对象');
                }
            });

        });
    }
}
